//
//  SubAuthView.m
//  SdkDemo
//
//  Created by HalloWorld on 2017/6/6.
//  Copyright © 2017年 legendsec. All rights reserved.
//

#import "SubAuthView.h"
#import <SecurePortal/SPVPNClient.h>

@interface AuthItemUITextField : UITextField
@property (nonatomic, copy) NSString* identify;
@end

@implementation AuthItemUITextField

@end

@interface SubAuthView()<UITextFieldDelegate,UIScrollViewDelegate>
{
    UILabel* _messageLabel;
    AuthItemUITextField* _value1TextField;
    AuthItemUITextField* _value2TextField;
    UIButton* _sendButton;
    
    UIScrollView* _scrollView;
    UIPageControl* _pageControl;
    
    BOOL _isQrcodeAuth;
}
@end


@implementation SubAuthView

- (UIImage*)imageWithColor:(UIColor*)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        self.backgroundColor = [UIColor whiteColor];
        
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.autoresizingMask = 0xFF;
        _scrollView.contentMode = UIViewContentModeCenter;
        _scrollView.contentSize = CGSizeMake(1 * CGRectGetWidth(_scrollView.frame), CGRectGetHeight(_scrollView.frame));
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:_scrollView];
        
        UIView* authInputView = [[UIView alloc] initWithFrame:self.bounds];
        authInputView.backgroundColor = [UIColor clearColor];
        [_scrollView addSubview:authInputView];
        
        UIFont* textFont = [UIFont systemFontOfSize:12];
        CGSize textInputSize = CGSizeMake(self.frame.size.width, 30);
        
        _messageLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.bounds.size.width-textInputSize.width)/2, 0, textInputSize.width,textInputSize.height)];
        _messageLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleWidth;
        _messageLabel.numberOfLines = 0;
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.font = textFont;
        _messageLabel.text = @"请输入用户名和密码";
        [self addSubview:_messageLabel];
        
        CGFloat cellOffsetY = 8;
        _value1TextField = [[AuthItemUITextField alloc] initWithFrame:CGRectMake((self.bounds.size.width-textInputSize.width)/2, 30, textInputSize.width,textInputSize.height)];
        _value1TextField.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleWidth;
        [_value1TextField setBackgroundColor:[UIColor clearColor]];
        _value1TextField.delegate = self;
        _value1TextField.font = textFont;
        [_value1TextField setReturnKeyType:UIReturnKeyNext];
        [_value1TextField setBorderStyle:UITextBorderStyleRoundedRect];
        [authInputView addSubview:_value1TextField];
        
        _value2TextField = [[AuthItemUITextField alloc] initWithFrame:CGRectMake(_value1TextField.frame.origin.x, CGRectGetMaxY(_value1TextField.frame)+cellOffsetY,_value1TextField.frame.size.width,_value1TextField.frame.size.height)];
        
        _value2TextField.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleWidth;
        [_value2TextField setBackgroundColor:[UIColor clearColor]];
        _value2TextField.delegate = self;
        _value2TextField.font = textFont;
        [_value2TextField setSecureTextEntry:YES];
        [_value2TextField setReturnKeyType:UIReturnKeyDone];
        [_value2TextField setBorderStyle:UITextBorderStyleRoundedRect];
        [authInputView addSubview:_value2TextField];
        
        UIColor* textColor = [UIColor whiteColor];
        UIColor* textHColor = [UIColor lightTextColor];
        
        _sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _sendButton.frame = CGRectMake(_value2TextField.frame.origin.x+CGRectGetMaxX(_value2TextField.bounds)-textInputSize.height*2.0, _value2TextField.frame.origin.y, textInputSize.height*2.0, textInputSize.height);
        _sendButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin;
        _sendButton.backgroundColor = [UIColor clearColor];
        
        _sendButton.layer.cornerRadius = 4.0;
        _sendButton.layer.masksToBounds = YES;
        
        UIImage* sendBtnImage = [self imageWithColor:[UIColor colorWithRed:69.0/255.0 green:188.0/255.0 blue:250.0/255.0 alpha:1.0] size:_sendButton.frame.size];
        UIImage* sendBtnImageH = [self imageWithColor:[UIColor colorWithRed:22.0/255.0 green:89.0/255.0 blue:209.0/255.0 alpha:1.0] size:_sendButton.frame.size];
        [_sendButton setBackgroundImage:sendBtnImage forState:UIControlStateNormal];
        [_sendButton setBackgroundImage:sendBtnImageH forState:UIControlStateHighlighted];
        
        _sendButton.titleLabel.font = textFont;
        _sendButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        [_sendButton setTitleColor:textColor forState:UIControlStateNormal];
        [_sendButton setTitleShadowColor:textHColor forState:UIControlStateNormal];
        [_sendButton setTitle:@"获取" forState:UIControlStateNormal];
        
        [_sendButton addTarget:self action:@selector(sendButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [authInputView addSubview:_sendButton];
        
        _value2TextField.frame = CGRectMake(_value2TextField.frame.origin.x,
                                            _value2TextField.frame.origin.y,
                                            _value1TextField.frame.size.width-_sendButton.frame.size.width-4,
                                            _value1TextField.frame.size.height);
    }
    return self;
}

- (void)setMessage:(NSString*)message
{
    _messageLabel.text = message;
}

- (void)updateFillItem:(NSDictionary*)fillItem
{
    if([_value1TextField.identify isEqualToString:[fillItem objectForKey:SPSDKSubAuthNeedValueKey]])
    {
        _value1TextField.text = [fillItem objectForKey:SPSDKSubAuthNeedValue];
    }
    else if([_value2TextField.identify isEqualToString:[fillItem objectForKey:SPSDKSubAuthNeedValueKey]])
    {
        NSInteger fillType = [[_authInfo objectForKey:SPSDKSubAuthType] integerValue];
        if(fillType == SPNextAuthTOTP)
        {
            _value2TextField.text = [NSString stringWithFormat:@"%@%@", _value2TextField.text, [fillItem objectForKey:SPSDKSubAuthNeedValue]];
        }
        else
        {
            _value2TextField.text = [fillItem objectForKey:SPSDKSubAuthNeedValue];
        }
    }
}

- (void)setAuthInfo:(NSDictionary *)authInfo
{
    NSLog(@"authInfo = %@", authInfo);
    
    _authInfo = authInfo;
    
    if(!_authInfo)
    {
        _value1TextField.text = @"";
        _value2TextField.text = @"";
        return;
    }
    
    BOOL sendButtonHide = YES;
    [_value2TextField setSecureTextEntry:NO];
    [_sendButton setHidden:YES];
    
    NSString* textTield2Placehodler = @"";
    
    NSInteger fillType = [[authInfo objectForKey:SPSDKSubAuthType] integerValue];
    switch (fillType) {
        case SPNextAuthUsernameAndPassword:
            _value1TextField.placeholder = @"请输入用户名";
            _value2TextField.placeholder = @"请输入密码";
            [_value2TextField setSecureTextEntry:YES];
            break;
        case SPNextAuthCerAndPassword:
            _value1TextField.placeholder = @"请选择证书文件";
            _value2TextField.placeholder = @"请输入证书密码";
            [_value2TextField setSecureTextEntry:YES];
            break;
        case SPNextAuthPassword:
            _value2TextField.placeholder = @"请输入密码";
            [_value2TextField setSecureTextEntry:YES];
            break;
        case SPNextAuthTOTP:
            if([_authInfo objectForKey:SPSDKSubAuthIAMFlag])
            {
                NSInteger iamFlag = [[_authInfo objectForKey:SPSDKSubAuthIAMFlag] integerValue];
                if(iamFlag == 1)
                {
                    textTield2Placehodler = @"请输入360ID密码+动态口令";
                }
                else if(iamFlag == 2)
                {
                    textTield2Placehodler = @"请输入前缀+360ID动态口令";
                }
            }
            if(textTield2Placehodler.length == 0)
            {
                textTield2Placehodler = @"请输入360ID动态口令";
            }
            _value1TextField.placeholder = @"请输入用户名";
            _value2TextField.placeholder = textTield2Placehodler;
            
            _value1TextField.placeholder = @"请输入用户名";
            _value2TextField.placeholder = @"请输入动态口令";
            [_sendButton setHidden:NO];
            sendButtonHide = NO;
            break;
        case SPNextAuthNeedPhoneNum:
            _value1TextField.placeholder = @"请输入手机号码";
            _value2TextField.placeholder = @"请输入验证码";
            [_sendButton setHidden:NO];
            sendButtonHide = NO;
            break;
        case SPNextAuthNeedEMailAddr:
            _value1TextField.placeholder = @"请输入邮箱地址";
            _value2TextField.placeholder = @"请输入验证码";
            [_sendButton setHidden:NO];
            sendButtonHide = NO;
            break;
        case SPNextAuthNeedVCCodeSMS:
        case SPNextAuthNeedVCCodeEMail:
            _value2TextField.placeholder = @"请输入验证码";
            break;
        case SPNextAuthQRCodeGetQrData:
            break;
        default:
            break;
    }
    
    if(sendButtonHide)
    {
        _value2TextField.frame = CGRectMake(_value2TextField.frame.origin.x,
                                            _value2TextField.frame.origin.y,
                                            _value1TextField.frame.size.width,
                                            _value1TextField.frame.size.height);
    }
    else
    {
        _value2TextField.frame = CGRectMake(_value2TextField.frame.origin.x,
                                            _value2TextField.frame.origin.y,
                                            _value1TextField.frame.size.width-_sendButton.frame.size.width-4,
                                            _value1TextField.frame.size.height);
    }
    
    [_value1TextField setHidden:YES];
    [_value2TextField setHidden:YES];
    
    NSArray* values = [authInfo objectForKey:SPSDKSubAuthNeedValues];
    if(values)
    {
        if([values count] == 1)
        {
            NSDictionary* fillItem = [values objectAtIndex:0];
            [_value2TextField setHidden:NO];
            _value2TextField.identify = [fillItem objectForKey:SPSDKSubAuthNeedValueKey];
            _value2TextField.text = [fillItem objectForKey:SPSDKSubAuthNeedValue];
        }
        if([values count] == 2)
        {
            NSDictionary* fillItem1 = [values objectAtIndex:0];
            [_value1TextField setHidden:NO];
            _value1TextField.identify = [fillItem1 objectForKey:SPSDKSubAuthNeedValueKey];
            _value1TextField.text = [fillItem1 objectForKey:SPSDKSubAuthNeedValue];
            
            NSDictionary* fillItem2 = [values objectAtIndex:1];
            [_value2TextField setHidden:NO];
            _value2TextField.identify = [fillItem2 objectForKey:SPSDKSubAuthNeedValueKey];
            _value2TextField.text = [fillItem2 objectForKey:SPSDKSubAuthNeedValue];
        }
    }
    
    NSInteger qrFlag = 0;
    if([_authInfo objectForKey:SPSDKSubAuthQrFlag])
    {
        qrFlag = [[_authInfo objectForKey:SPSDKSubAuthQrFlag] integerValue];
    }
    
    if(qrFlag == 1)
    {
        if(!_pageControl)
        {
            _pageControl = [[UIPageControl alloc] init];
            _pageControl.frame = CGRectMake((self.bounds.size.width-20)/2, self.bounds.size.height, 20, 20);
            _pageControl.backgroundColor = [UIColor clearColor];
            _pageControl.numberOfPages = 2;
            _pageControl.currentPage = 0;
            _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
            _pageControl.currentPageIndicatorTintColor = [UIColor colorWithRed:8.0/255.0 green:129.0/255.0 blue:218.0/255.0 alpha:1.0];
            [self addSubview:_pageControl];
        }
        
        _scrollView.contentSize = CGSizeMake(2 * CGRectGetWidth(_scrollView.frame),
                                             CGRectGetHeight(_scrollView.frame));
        
        UIView* qrcodeAuthView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.bounds),
                                                                          self.bounds.origin.y,
                                                                          self.bounds.size.width,
                                                                          self.bounds.size.height)];
        qrcodeAuthView.backgroundColor = [UIColor clearColor];
        CGSize qrcodeAuthImageSize = CGSizeMake(qrcodeAuthView.bounds.size.height*0.4, qrcodeAuthView.bounds.size.height*0.4);
        UIImageView* qrcodeAuthImageView = [[UIImageView alloc] initWithFrame:CGRectMake(qrcodeAuthView.bounds.size.width*0.1,(qrcodeAuthView.bounds.size.height-qrcodeAuthImageSize.height)/2, qrcodeAuthImageSize.width, qrcodeAuthImageSize.height)];
        qrcodeAuthImageView.image = [UIImage imageNamed:@"sslvpnsdk.bundle/sportal_login_secid_normal"];
        [qrcodeAuthView addSubview:qrcodeAuthImageView];
        
        UILabel* qrcodeAuthLabel = [[UILabel alloc] initWithFrame:CGRectMake(qrcodeAuthView.bounds.size.width*0.1+qrcodeAuthImageSize.width+8.0,(qrcodeAuthView.bounds.size.height-qrcodeAuthImageSize.height)/2, qrcodeAuthView.bounds.size.width*0.8-qrcodeAuthImageSize.width, qrcodeAuthImageSize.height)];
        qrcodeAuthLabel.numberOfLines = 0;
        qrcodeAuthLabel.textAlignment = NSTextAlignmentLeft;
        qrcodeAuthLabel.text = @"使用二维码认证";
        [qrcodeAuthView addSubview:qrcodeAuthLabel];
        
        [_scrollView addSubview:qrcodeAuthView];
    }
    else
    {
        if(_pageControl)
        {
            [_pageControl removeFromSuperview];
            _pageControl = nil;
        }
        _scrollView.contentSize = CGSizeMake(1 * CGRectGetWidth(_scrollView.frame),
                                             CGRectGetHeight(_scrollView.frame));
    }
}

#pragma mark button action

- (void)inputValueAndDoNextAction
{
    if(self.doSubAuthBlock)
    {
        if(_isQrcodeAuth)
        {
            NSMutableDictionary* newAuthInfo = [NSMutableDictionary
                                                dictionaryWithDictionary:self.authInfo];
            [newAuthInfo setObject:[NSNumber numberWithInteger:SPNextAuthQRCodeGetQrData]
                            forKey:SPSDKSubAuthType];
            
            self.doSubAuthBlock(self, newAuthInfo, nil);
        }
        else
        {
            NSMutableArray* fillValues = nil;
            if(![_value1TextField isHidden])
            {
                if(_value1TextField.text.length == 0)
                {
                    NSString* tips = [self.authInfo objectForKey:SPSDKSubAuthDesc];
                    if(self.doSubAuthError)
                    {
                        self.doSubAuthError(self, tips);
                    }
                    return;
                }
                
                if(!fillValues)
                {
                    fillValues = [NSMutableArray arrayWithCapacity:2];
                }
                NSDictionary* fillDic = @{ SPSDKSubAuthNeedValueKey : _value1TextField.identify,
                                           SPSDKSubAuthNeedValue : _value1TextField.text };
                [fillValues addObject:fillDic];
            }
            
            if(![_value2TextField isHidden])
            {
                if(_value2TextField.text.length == 0)
                {
                    NSInteger fillType = [[self.authInfo objectForKey:SPSDKSubAuthType] integerValue];
                    if(fillType != SPNextAuthNeedPhoneNum &&
                       fillType != SPNextAuthNeedEMailAddr)
                    {
                        NSString* tips = [self.authInfo objectForKey:SPSDKSubAuthDesc];
                        if(self.doSubAuthError)
                        {
                            self.doSubAuthError(self, tips);
                        }
                        return;
                    }
                }
                
                if(_value2TextField.text.length > 0)
                {
                    if(!fillValues)
                    {
                        fillValues = [NSMutableArray arrayWithCapacity:2];
                    }
                    NSDictionary* fillDic = @{ SPSDKSubAuthNeedValueKey : _value2TextField.identify,
                                               SPSDKSubAuthNeedValue : _value2TextField.text };
                    [fillValues addObject:fillDic];
                }
            }
            
            self.doSubAuthBlock(self, self.authInfo, fillValues);
        }
    }
}

- (void)sendButtonClicked:(id)sender
{
    NSInteger fillType = [[_authInfo objectForKey:SPSDKSubAuthType] integerValue];
    switch (fillType) {
        case SPNextAuthTOTP:
            if(self.getTotpBlock) {
                self.getTotpBlock(self, _value1TextField.text);
            }
            break;
        case SPNextAuthNeedPhoneNum:
            [self inputValueAndDoNextAction];
            break;
        case SPNextAuthNeedEMailAddr:
            [self inputValueAndDoNextAction];
            break;
        default:
            break;
    }
}

- (void)authButtonClicked:(id)sender
{
    [self inputValueAndDoNextAction];
}

#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _value1TextField)
    {
        [_value2TextField becomeFirstResponder];
    }
    else
    {
        if(_value1TextField && [_value1TextField canResignFirstResponder])
        {
            [_value1TextField resignFirstResponder];
        }
        
        if(_value2TextField && [_value2TextField canResignFirstResponder])
        {
            [_value2TextField resignFirstResponder];
        }
    }
    return YES;
}

#pragma mark -
#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger page = scrollView.contentOffset.x / scrollView.frame.size.width;
    if(page == 1)
    {
        _isQrcodeAuth = YES;
        _messageLabel.text = @"360ID安全登录";
    }
    else
    {
        _isQrcodeAuth = NO;
        _messageLabel.text = [_authInfo objectForKey:SPSDKSubAuthDesc];
    }
    _pageControl.currentPage = page;
}

@end
